<script setup lang="ts">
import { getHomeBannerAPI, getHomeCategoryMutilAPI, getHomeHotMutilAPI } from '@/services/home'
import type { BannerItem, CategoryItem, HotItem } from '@/types/home'
import CustomNavBar from './component/CustomNavbar.vue'
import CategoryPanel from './component/CategoryPanel.vue'
import HotPanel from './component/HotPanel.vue'
import Sketeton from './component/Skeleton.vue'
import { useGuessList } from '@/composables'
import { onLoad } from '@dcloudio/uni-app'
import { ref } from 'vue'

//定义一个变量，接收轮播图列表数据
const bannerList = ref<BannerItem[]>([])
//获取首页轮播图方法
const getHomeBannerData = async () => {
  const res = await getHomeBannerAPI()
  bannerList.value = res.result
}

const categoryMutilList = ref<CategoryItem[]>([])
//获取前台分类小程序
const getHomeCategoryMutilDate = async () => {
  const res = await getHomeCategoryMutilAPI()
  categoryMutilList.value = res.result
}

const hotMutilList = ref<HotItem[]>([])
//获取热门推荐
const getHotMutilDate = async () => {
  const res = await getHomeHotMutilAPI()
  hotMutilList.value = res.result
}
//通过组合式
const { guessRef, onScrolltolower } = useGuessList()
const refresherFlag = ref(false)
//滚动容器实现下拉刷新 思路：1.滚动容器 2.开启下拉刷新 3.监听事件 4.加载数据 5.关闭动画
const onRefresherrefresh = async () => {
  refresherFlag.value = true

  //重新获取一遍数据  还有猜你喜欢组件内部的数据
  // await getDate()

  //重置猜你喜欢查询条件
  guessRef.value.resetDate()

  //或者同步发送
  await Promise.all([
    getHomeBannerData(),
    getHomeCategoryMutilDate(),
    getHotMutilDate(),
    guessRef.value.getMore(),
  ])
  //主动关闭下拉动画
  refresherFlag.value = false
}

const loading = ref(false)
//组件初始化方法
onLoad(async () => {
  //数据未加载前，将loading设置为true
  loading.value = true
  //初始化的时候，调用轮播图接口
  await getDate()

  //模拟网络卡顿，等待两秒
  // setTimeout(() => {
  //   loading.value = false
  // }, 2000)

  //数据全部不加载后，将loading 设置为false
  loading.value = false
})

const getDate = async () => {
  getHomeBannerData()
  getHomeCategoryMutilDate()
  getHotMutilDate()
}
</script>

<template>
  <!-- 自定义导航栏 -->
  <CustomNavBar />
  <!-- 定义一个滚动容器，导航栏不滚动，其他支持滚动
  @scrolltolower:滚动触底调用的方法
   @refresherrefresh +refresher-enabled 实现下拉刷新
   -->
  <scroll-view
    @scrolltolower="onScrolltolower"
    :refresher-triggered="refresherFlag"
    refresher-enabled
    @refresherrefresh="onRefresherrefresh"
    class="scroll-view"
    scroll-y
  >
    <!-- 骨架屏显示 -->
    <Sketeton v-if="loading" />
    <template v-else>
      <!-- 轮播图通用组件 通用配置-->
      <ZySwiper :list="bannerList" />
      <!-- 分类面板组件 -->
      <CategoryPanel :list="categoryMutilList" />
      <!-- 热门推荐组件 -->
      <HotPanel :list="hotMutilList" />
      <!-- 猜你喜欢  通用配置-->
      <ZyGuess ref="guessRef" />
    </template>
  </scroll-view>
</template>

<style lang="scss">
//
page {
  // 设置页面的背景颜色
  background-color: #f7f7f7;
  //设置高度  通过以下css样式，设置导航栏固定
  height: 100%;
  display: FLEX;
  flex-direction: column;
}
.scroll-view {
  flex: 1;
}
</style>
